import { GlobalFunction } from "../base/GlobalFunction";
import { GlobalEvent } from "../base/GlobalEvent";
import { ConstData } from "../base/ConstData";

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Node)
    sword:cc.Node = null;
    @property(cc.PolygonCollider)
    range:cc.PolygonCollider = null;

    private speed:number = 10;
    private touchPos:cc.Vec2;
    private isAttackMode:boolean = false;

    onLoad () {
        GlobalEvent.on(GlobalEvent.Event.swtichAttackMode, this.swtichAttackMode.bind(this),this);
    }

    swtichAttackMode(Event){
        if(Event){
            this.touchPos = this.sword.position;
            this.node.on(cc.Node.EventType.TOUCH_START, this.onTouch, this);
            this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouch, this);
            this.node.on(cc.Node.EventType.TOUCH_END, this.onTouch, this);
            this.isAttackMode = true;
        }
        else
        {
            this.node.off(cc.Node.EventType.TOUCH_START, this.onTouch, this);
            this.node.off(cc.Node.EventType.TOUCH_MOVE, this.onTouch, this);
            this.node.off(cc.Node.EventType.TOUCH_END, this.onTouch, this);
            this.isAttackMode = false;
        }
    }

    onTouch(event){
        this.touchPos = GlobalFunction.UIPosToMapNodePos(this.sword, event.touch.getLocation());
    }

    update(){
        if(!this.isAttackMode) return;
        var dis = GlobalFunction.getTwoPointDis(this.touchPos, this.sword.position);
        if(dis >= 10){
            if(!cc.Intersection.pointInPolygon(this.sword.convertToWorldSpaceAR(cc.v2(0,0)), this.range.world.points)) {
                this.touchPos = GlobalFunction.getWorldMgr().getPlayer().position;
            }
            var dirVec = GlobalFunction.getTwoPointVec( this.touchPos, this.sword.position);
            dirVec.scale(cc.v2(this.speed, this.speed), dirVec);
            this.sword.getComponent(cc.RigidBody).linearVelocity = dirVec;
        }
        else
        {
            this.sword.getComponent(cc.RigidBody).linearVelocity = cc.v2(0,0);
        }
    }
}
